package view.components.table;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.JTable;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumnModel;



/**
 * TableHeader der sich die zuletzt angewendete Sortierung merkt
 */
public class MemorizingJTableHeader extends JTableHeader {
	private static final long serialVersionUID = -745552602474601072L;
	private List<ColumnHeaderListener> _listeners = new ArrayList<ColumnHeaderListener>();
	private int lastIndex;
	private boolean isAscending;
	public static final int ASCENDING = 0;
	public static final int DESCENDING = 1;

	public MemorizingJTableHeader() {
		super();
		lastIndex = -1;
		isAscending = true;
	}

	public MemorizingJTableHeader(TableColumnModel model) {
		super(model);
		lastIndex = -1;
		isAscending = true;
	}

	public MemorizingJTableHeader(int filterIndex) {
		super();
		lastIndex = filterIndex;
		isAscending = true;
	}

	public MemorizingJTableHeader(TableColumnModel model, int filterIndex) {
		super(model);
		lastIndex = filterIndex;
		isAscending = true;
	}

	public synchronized void setSortOrder(int order) {
		switch (order) {
			case 0 :
				this.isAscending = true;
				return;
			case 1 :
				this.isAscending = false;
				return;
			default :
				this.isAscending = true;

		}
	}

	public synchronized void addColumnHeaderListener(ColumnHeaderListener l) {
		_listeners.add(l);
		this.addMouseListener(new MouseAdapter() {

			@Override
			public void mouseClicked(MouseEvent e) {
				JTableHeader tableHeader = (JTableHeader) e.getSource();
				JTable table = tableHeader.getTable();
				TableColumnModel colModel = table.getColumnModel();
				int buffer = colModel.getColumnIndexAtX(e.getX());
				if (buffer == lastIndex) {
					isAscending = !isAscending;
				} else {
					isAscending = true;
				}
				lastIndex = buffer;
				fireHeaderChangedEvent();
			}
		});
	}

	public synchronized void removeColumnHeaderListener(ColumnHeaderListener l) {
		_listeners.remove(l);
	}

	private synchronized void fireHeaderChangedEvent() {

		HeaderEvent evt = new HeaderEvent(this, lastIndex, isAscending);
		Iterator<ColumnHeaderListener> listeners = _listeners.iterator();
		while (listeners.hasNext()) {
			((ColumnHeaderListener) listeners.next()).HeaderChanged(evt);
		}
	}

}
